const {
	getRandomId,
} = require('../../dbUtils')
const {
	getTime,
} = require('../../dateUtils')
const {
	getModuleTree,
} = require('./utils')
const _cmsMongo = global._cmsMongo

module.exports = {

	userAdd(params) {
		return userAdd(params)
	},

	userModify(params) {
		return userModify(params)
	},

	userDel(params) {
		return userDel(params)
	},

	login(params) {
		return login(params)
	},

	getUser(params) {
		return getUser(params)
	},

	getUserList(params, role_ids) {
		return getUserList(params, role_ids)
	},
}

/**
 * 添加用户
 * @param  {[type]} params [description]
 * @return {[type]}        [description]
 */
async function userAdd(params) {
	let {
		username,
		nickname = '',
		pic = '',
		mobile = '',
		mail = '',
		desc = '',
	} = params
	let userCol = await _cmsMongo.getCollection('user')
	let user = await userCol.findOne({
		username,
	})
	// 用户存在
	if (user && user._id)
		return -1
	let password = getRandomId(6)
	user = {
		user_id: getRandomId(),
		username,
		nickname,
		pic,
		password,
		orgpassword: password,
		mobile,
		mail,
		desc,
		role_ids: [],
		create_time: getTime(),
		modify_time: getTime(),
	}
	userCol.insertOne(user)
	return user
}

/**
 * 用户信息修改
 * @param  {[type]} params [description]
 * @return {[type]}        [description]
 */
async function userModify(params) {
	let {
		username,
	} = params
	let userCol = await _cmsMongo.getCollection('user')
	let user = await userCol.findOne({
		username,
	})
	if (!user || !user._id)
		return -1
	let set = {}
	if (params.nickname)
		set.nickname = params.nickname
	if (params.pic)
		set.pic = params.pic
	if (params.mobile)
		set.mobile = params.mobile
	if (params.mail)
		set.mail = params.mail
	if (params.desc)
		set.desc = params.desc
	set.modify_time = getTime()
	return userCol.findOneAndUpdate({
		_id: user._id,
	}, {
		$set: set,
	})
}

async function userDel(params) {
	let {
		user_id,
	} = params
	let userCol = await _cmsMongo.getCollection('user')
	if (user_id == '00000000')
		return false
	return userCol.deleteOne({
		user_id,
	})
}

/**
 * 用户登录
 * @param  {[type]} params [description]
 * @return {[type]}        [description]
 */
async function login(params) {
	let user = await getUser(params)
	let userCol = await _cmsMongo.getCollection('user')
	await userCol.updateOne({
		_id: user && user._id || '',
	}, {
		$set: {
			last_login_date: getTime(),
		}
	})
	return user
}

/**
 * 用户信息
 * @param  {[type]} params [description]
 * @return {[type]}        [description]
 */
async function getUser(params) {
	let {
		uid,
		username,
		password,
		mobile,
	} = params
	if (!uid && !password && (!username || !mobile))
		return null
	let userCol = await _cmsMongo.getCollection('user')
	let query = {}
	if (uid) {
		query._id = _cmsMongo.ObjectID(uid)
	} else {
		query.password = password
		if (mobile)
			query.mobile = mobile
		if (username)
			query.username = username
	}
	let user = await userCol.findOne(query)
	if (!user || !user._id)
		return null
	let userMenu = await getUserMenu(user.role_ids)
	user.menuTree = userMenu.menuTree
	user.funcMap = userMenu.funcMap
	user.moduleFuncMap = userMenu.moduleFuncMap
	user.func_ids = userMenu.func_ids
	return user
}

/**
 * 用户列表
 * @param  {[type]} params   [description]
 * @param  {[type]} role_ids [description]
 * @return {[type]}          [description]
 */
async function getUserList(params, role_ids) {
	let {
		ps,
		pn = 1,
	} = params
	let userCol = await _cmsMongo.getCollection('user')
	let limit = ps || 1000
	let skip = (pn - 1) * limit
	let query = {}
	if (role_ids.indexOf('admin') < -1)
		query.role_id = {
			$ne: 'admin'
		}
	let total = await userCol.count()
	let rows = await userCol.find().skip(skip).limit(limit).toArray()
	return {
		total,
		rows,
	}
}

/**
 * 按权限获取用户菜单
 * @param  {[type]} role_ids [description]
 * @return {[type]}          [description]
 */
async function getUserMenu(role_ids) {
	let menuMap = {
		menuTree: [],
		funcMap: {},
		moduleFuncMap: {},
		func_ids: [],
	}
	if (!Array.isArray(role_ids))
		return menuMap
	// admin为超级用户
	if (role_ids.indexOf('admin') > -1)
		return getAdminMenu(menuMap)
	let roleCol = await _cmsMongo.getCollection('role')
	let funcCol = await _cmsMongo.getCollection('func')
	// 用户角色(可多个)对应功能
	let roleList = await roleCol.find({
		role_id: {
			$in: role_ids,
		}
	}, {
		func_ids: 1,
	}).toArray()
	let role = roleList.shift()
	let funcIdSet = new Set()
	while (role && Array.isArray(role.func_ids)) {
		role.func_ids.forEach(val => funcIdSet.add(val))
		role = roleList.shift()
	}
	// 功能对应模块
	let funcList = await funcCol.find({
		func_id: {
			$in: Array.from(funcIdSet)
		}
	}, {
		create_time: 0,
		modify_time: 0,
	}).toArray()
	let moduleSet = new Set()
	for (let i = 0; i < funcList.length; i++) {
		let func = funcList[i]
		moduleSet.add(func.module_id)
		menuMap.moduleFuncMap[func.module_id] = menuMap.moduleFuncMap[func.module_id] || {}
		menuMap.moduleFuncMap[func.module_id][func.func_id] = func
		menuMap.funcMap[func.func_id] = func
		menuMap.func_ids.push(func.func_id)
	}
	// 模块id
	let moduleIds = Array.from(moduleSet)
	let moduleList = await getModuleTree()
	for (let i = 0; i < moduleList.length; i++) {
		let module = moduleList[i]
		let newChildren = parseRootModule(module, moduleIds)
		if (newChildren && newChildren.length > 0) {
			module.children = newChildren
			menuMap.menuTree.push(module)
		}
	}
	return menuMap
}

function parseRootModule(module, moduleIds) {
	let children = module.children
	let newChildren = []
	for (let i = 0; i < children.length; i++) {
		let child = children[i]
		if (moduleIds.indexOf(child.module_id) > -1) {
			newChildren.push(child)
			continue
		}
		if (Array.isArray(child.children)) {
			let nc = parseRootModule(child, moduleIds)
			if (nc && nc.length > 0) {
				child.children = nc
				newChildren.push(child)
			}
		}
	}
	return newChildren
}

/**
 * 按权限获取模块列表
 * @param  {[type]} role_ids [description]
 * @return {[type]}          [description]
 */
async function getAdminMenu(menuMap) {
	let funcCol = await _cmsMongo.getCollection('func')
	let funcList = await funcCol.find({}, {
		create_time: 0,
		modify_time: 0,
	}).toArray()
	for (let i = 0; i < funcList.length; i++) {
		let func = funcList[i]
		menuMap.moduleFuncMap[func.module_id] = menuMap.moduleFuncMap[func.module_id] || {}
		menuMap.moduleFuncMap[func.module_id][func.func_id] = func
		menuMap.funcMap[func.func_id] = func
		menuMap.func_ids.push(func.func_id)
	}
	menuMap.menuTree = await getModuleTree()
	return menuMap
}